package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.ConstConstants;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> senMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            System.out.println(code);
//            SMSUtils.sendMessage("瑞吉外卖","",phone,code);
            session.setAttribute(phone,code);
            return R.success("发送成功");
        }

        return R.error("发送失败");
    }
    @PostMapping("/login")
    public R<User>login(@RequestBody Map user,HttpSession session){
        String phone = (String)user.get("phone");
//        String code = (String)user.get("code");
        Object codeInSession = session.getAttribute(phone);
//        if(code.equals("123")){
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper();
            queryWrapper.eq(User::getPhone,phone);
            User user1 = userService.getOne(queryWrapper);
            if(user1==null){
                user1=new User();
                user1.setPhone(phone);
                user1.setStatus(1);
                userService.save(user1);
            }
            session.setAttribute(ConstConstants.USER_ID_IN_SESSION,user1.getId());
            return R.success(user1);
//        }
    }

}
